package org.example.service;

import com.bonree.cmdb.service.BidirectionalServiceGrpc;
import com.bonree.cmdb.service.ClientDemoRequest;
import com.bonree.cmdb.service.ServerDemoResponse;
import io.grpc.stub.StreamObserver;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author wangjun
 * @Date 2025/3/17 18:35
 */
@Service
public class GrpcClientServiceImpl {

    private GrpcClientDemo grpcClient = null;

    public GrpcClientServiceImpl() {
        Map<String, Integer> serverMap = new HashMap<>(2);
        serverMap.put("localhost", 6661);
        serverMap.put("127.0.0.1", 8882);
        grpcClient = new GrpcClientDemo(serverMap);
    }

    public String testBidirectionalService(String requestId, String endId, GrpcCallback grpcCallback) {
        try {
            BidirectionalServiceGrpc.BidirectionalServiceStub bidirectionalServiceStub = BidirectionalServiceGrpc.newStub(grpcClient.next());
            // 准备响应流处理器
            StreamObserver<ServerDemoResponse> responseObserver = new StreamObserver<ServerDemoResponse>() {
                @Override
                public void onNext(ServerDemoResponse response) {
                    System.out.println("客户端收到: " + response.getReply());
                    grpcCallback.onSuccess("success");
                }

                @Override
                public void onError(Throwable t) {
                    System.err.println("客户端流错误: " + t.getMessage());
                    System.out.println(t.getMessage().equals("UNKNOWN"));
                }

                @Override
                public void onCompleted() {
                    System.out.println("客户端流结束");
                }
            };

            // 发起双向流调用，获取请求流处理器
            StreamObserver<ClientDemoRequest> requestObserver = bidirectionalServiceStub.chat(responseObserver);
            // 发送多个请求
            ClientDemoRequest request = ClientDemoRequest.newBuilder().setMessage("客户端发送消息").build();
            requestObserver.onNext(request);
            requestObserver.onCompleted();
            return "success";
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
